﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;

namespace Monitor.Utils
{
    static public class ProcessUtils
    {
        #region Win32 API For Window Information
        // API calls to give us a bit more information about the data we get from the hook
        [DllImport("user32.dll")]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder title, int size);
        [DllImport("user32.dll")]
        private static extern uint RealGetWindowClass(IntPtr hWnd, StringBuilder pszType, uint cchType);
        [DllImport("user32.dll")]
        private static extern void GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
        #endregion

        public static string GetWindowName(IntPtr Hwnd)
        {
            // This function gets the name of a window from its handle
            StringBuilder Title = new StringBuilder(1024);
            GetWindowText(Hwnd, Title, 1024);

            return Title.ToString().Trim();
        }

        public static bool isExplorer(IntPtr handle)
        {
            return isFromProcess(handle, "explorer");
        }

        private static bool isFromProcess(IntPtr handle, string processName)
        {
            uint pid;
            GetWindowThreadProcessId(handle, out pid);

            Process[] processes = Process.GetProcessesByName(processName);
            if (processes.Length != 1)
                return false;

            if (pid == processes[0].Id)
                return true;

            return false;
        }

        public static List<String> GetAllDriveLetters()
        {
            List<String> ans = new List<String>();
            foreach(DriveInfo drive in DriveInfo.GetDrives())
                ans.Add(drive.Name);
            return ans;
        }

        public static bool isPath(String str, List<String> drives)
        {
            return isInList(str, drives);
        }

        public static bool isKnownLocation(String str, List<String> knownLocations)
        {
            return isInList(str, knownLocations);
        }

        private static bool isInList(String str, List<String> drives)
        {
            foreach (String drive in drives)
                if (str.StartsWith(drive))
                    return true;
            return false;
        }
    }
}
